<template>
  <div class="search-container">
    <!-- 搜索组件 -->

     <div class="search-box">
      <van-search class="search"  shape="round" v-model="keyword" placeholder="搜索歌曲、歌手、专辑"  @search="onSearch"
        @cancel="onCancel"
        :autofocus = "autoFoc"
        @focus="isResultShow=false"/>
    </div>

     <!-- 搜索结果 -->

    <search-result v-if="isResultShow" :keyword="keyword"></search-result>
     <!-- 联想建议 -->
    <search-suggesstion v-else-if="keyword" :keyword="keyword" @search="onSearch"></search-suggesstion>

    <!-- 搜索历史和热搜关键词 -->
    <search-history v-else @onchangeKey="onSearch" :searchHistories="searchHistories"  @search="onSearch"
      @clear-histories="searchHistories=[]"></search-history>

  </div>
</template>

<script>
import SearchHistory from '../components/Search/search-history.vue'
import SearchResult from '../components/Search/search-result.vue'
import SearchSuggesstion from '../components/Search/search-suggesstion.vue'
import { setItem } from '@/utils/index.js'

export default {

  data () {
    return {
      isResultShow: false,
      autoFoc: false,
      keyword: '', // 搜索关键词
      searchHistories: [] // 存储历史记录
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.autoFoc = true
    })
  },
  name: 'Search',
  beforeRouteEnter (to, from, next) {
    // console.log(to, from, next)

    if (to.path === '/search') {
      next(vm => {
        vm.$nextTick(() => {
          console.log(vm)
          // vm.autoFoc = true
        }, 200)
      })
    }
  },
  watch: {
    //      数据持久化
    // 利用 watch 监视统一存储数据
    searchHistory (val) {
      setItem('search-histories', val)
    }
  },
  created () {

  },

  methods: {
    // 获取搜索结果 存储历史记录

    // 存储历史记录
    // 要求：不要有重复的历史纪录最新的排在前面

    // 确认搜索时触发
    onSearch (val) {
      // 触发搜索结果
      console.log(val)
      this.keyword = val

      const index = this.searchHistories.indexOf(val)
      console.log(index)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.push(val)
      // 渲染搜索结果

      this.isResultShow = true
    },
    onCancel () {

    }
  },

  components: {
    SearchHistory,
    SearchSuggesstion,
    SearchResult

  }
}

</script>

<style lang="less" scoped>
.search-container{
  height: 100%;
}
 .search {

    border-bottom: 1px solid rgba(0, 0, 0, .1);
      background-color:#4a4a4a;
  }
</style>
